package controllers;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import models.Payroll;
import models.PayrollPeriod;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import play.mvc.Controller;
import service.CalculationResult;
import service.PayrollRegisterResult;
import service.PayrollRegisterService;

public class PayrollCashDownload extends Controller {

	@Inject
    private static PayrollRegisterService payrollRegisterService;

    public static void download(Long payrollPeriodId) {
        PayrollPeriod payrollPeriod = PayrollPeriod.findById(payrollPeriodId);
        createExcelSheet(payrollPeriod);
        export();
    }

    private static void createExcelSheet(PayrollPeriod payrollPeriod) {
        try {
            generateExcelDocument(payrollPeriod);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void generateExcelDocument(PayrollPeriod payrollPeriod)
            throws IOException {
        Workbook wb = new HSSFWorkbook();
        CreationHelper createHelper = wb.getCreationHelper();
        Sheet sheet = wb.createSheet("new sheet");

        /*
         * Create the header.
         */
        Row row = sheet.createRow((short) 0);
        Cell cell = row.createCell(0);
        cell.setCellValue(payrollPeriod.client.name);
        row = sheet.createRow((short) 1);
        cell = row.createCell(0);
        cell.setCellValue("Payroll Cash");
        row = sheet.createRow((short) 2);
        cell = row.createCell(0);
        cell.setCellValue(payrollPeriod.getFromDateFormatted() + " - "
                + payrollPeriod.getToDateFormatted());

        String electronicId = payrollPeriod.client.electronicId;

        /*
         * Create the Payment type header.
         */
        row = sheet.createRow((short) 4);
        int paymentDeductionTypeIndex = 1;

        /*
         * Net Pay.
         */
        cell = row.createCell(paymentDeductionTypeIndex);
        cell.setCellValue("Net Pay");

        /*
         * Iterate over employee and print its payments and deductions.
         */
        PayrollRegisterResult result = payrollRegisterService.process(
                electronicId, payrollPeriod);
        Map<Long, CalculationResult> calcResults = result
                .getCalculationResults();
        List<Payroll> payrolls = getPayrolls(payrollPeriod);
        short rowIndex = 5;
        for (Payroll payroll : payrolls) {
        	if (StringUtils.isEmpty(payroll.employee.atmNumber)) {
	            row = sheet.createRow(rowIndex);
	
	            int columnIndex = 0;
	            cell = row.createCell(columnIndex);
	            cell.setCellValue(payroll.employee.name);
	            columnIndex++;
	
	            Long employeeId = payroll.employee.id;
	            CellStyle style = wb.createCellStyle();
	            style.setAlignment(CellStyle.ALIGN_RIGHT);
	            style.setDataFormat(createHelper.createDataFormat().getFormat(
	                    "#,##0.00"));

	            /*
	             * Net pay.
	             */
	            CalculationResult calcResult = calcResults.get(employeeId);
	            cell = row.createCell(columnIndex);
	            cell.setCellValue(calcResult.netPay.doubleValue());
	            cell.setCellStyle(style);
	            cell.setCellType(Cell.CELL_TYPE_NUMERIC);

	            rowIndex++;
        	}
        }

        /*
         * Create and write the file.
         */
        DateFormat df = new SimpleDateFormat("MMMddyyyy");
        String fileName = "PayrollCash-"
                + df.format(payrollPeriod.fromDate) + '-'
                + df.format(payrollPeriod.toDate);
        df = new SimpleDateFormat("HHmmssMMMddyyyy");
        fileName = fileName + '-' + df.format(new Date());
        fileName = fileName + ".xls";
        FileOutputStream fileOut = new FileOutputStream(fileName);
        wb.write(fileOut);
        fileOut.close();
    }

    private static List<Payroll> getPayrolls(PayrollPeriod payrollPeriod) {
        return payrollRegisterService.loadPayrolls(payrollPeriod);
    }

    private static void export() {
        // TODO Auto-generated method stub
    }

}
